import config from "@/config";
import { useEffect, useRef } from "react";
import { Animated, ViewStyle, TextStyle, StyleProp, View, Text, StyleSheet, TouchableOpacity } from "react-native";

export type Props = {
  /**
   * 网络状态
   * 1 表示网络不通
   * 2 表示网络通, websocket 不通
   * 3 表示网络全通
   */
  state: "1" | "2" | "3";
  /** 显示的内容 */
  content: string;
  /** content 的样式 */
  contentStyles?: StyleProp<TextStyle>;
  /** 动画圆的样式 */
  AninViewStyles?: StyleProp<ViewStyle>;
  /** 容器样式 */
  containerStyles?: StyleProp<ViewStyle>;
  /** 点击事件 */
  onClick?: () => void;
};

/** 动画实例 */
let aca: Animated.CompositeAnimation | null = null;

// 底部网络圆点或设备编号
const NetworkState = (props: Props) => {
  // 透明度初始值 0.1
  const fadeAnim = useRef(new Animated.Value(0.1)).current;

  useEffect(() => {
    aca = Animated.loop(
      // 循环动画
      Animated.sequence([
        Animated.timing(fadeAnim, {
          toValue: 1, // 最终的值
          duration: 700, // 过渡时间
          useNativeDriver: true // 使用原生动画(不会阻塞主线程)
        }),
        Animated.timing(fadeAnim, {
          toValue: 0,
          duration: 700,
          useNativeDriver: true
        })
      ])
    );

    // 执行动画
    aca.start();

    return () => {
      if (aca) {
        aca.stop();
        aca = null;
      }
    };
  }, [fadeAnim, props.state]);

  // 颜色
  const colors = {
    "1": "red",
    "2": "yellow",
    "3": "green"
  };

  return (
    <TouchableOpacity style={[styles.container, props.containerStyles]} onPress={props.onClick}>
      <View style={styles.networkStateComtainer}>
        <Animated.View // 使用可动画化的 View组件
          style={[
            styles.networkState,
            {
              backgroundColor: colors[props.state],
              opacity: props.state === "3" ? 1 : fadeAnim // 将透明度绑定到动画变量值
            },
            props.AninViewStyles
          ]}
        />
        <View style={styles.serialNumberContainer}>
          <Text style={[styles.serialNumber, props.contentStyles, { color: colors[props.state] }]}>
            {props.content || "没有获取到编号"}
          </Text>
        </View>
      </View>
    </TouchableOpacity>
  );
};

const styles = StyleSheet.create({
  container: {
    backgroundColor: "#000",
    padding: 4,
    borderRadius: 4
  },
  networkStateComtainer: {
    alignItems: "center",
    gap: 3,
    flexDirection: "row"
  },
  networkState: {
    width: 14,
    height: 14,
    borderRadius: 7
  },
  networkText: {
    fontSize: 7,
    fontWeight: "bold",
    color: "red"
  },
  serialNumberContainer: {
    // backgroundColor: "rgba(255, 255, 255, .4)",
    // borderRadius: 4,
    // paddingLeft: 4,
    // paddingRight: 4
  },
  serialNumber: {
    color: "green",
    fontSize: 12,
    fontWeight: "bold"
  }
});

export default NetworkState;
